//  This product includes software developed by Denim Group, Ltd. (http://www.denimgroup.com/)
//  All use and distribution of the Denim Group developed software is subject to Version 2.0
//  of the Apache License (http://www.apache.org/licenses/LICENSE-2.0).

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AppScan;
using AppScan.Scan.Results;
using AppScan.Scan.Data;
using System.Collections;

namespace AppScan.DefectLogger
{
	public partial class IssueSelector : Form
	{

		// A member holding the selected issue
		private IIssue _selectedIssue = null;

		public IIssue SelectedIssue
		{
			get { return _selectedIssue; }
		}

		private int MapIssueTypeToImageIndex(IIssueType issueType)
		{
			if (issueType.Severity == Severity.High)
			{
				return 3;
			}
			if (issueType.Severity == Severity.Medium)
			{
				return 2;
			}
			if (issueType.Severity == Severity.Low)
			{
				return 4;
			}
			return 0;
		}

		public IssueSelector(IAppScan appScan, IIssueType issueType)
		{
			InitializeComponent();

			treeIssueSelector.BeginUpdate();
			treeIssueSelector.Nodes.Add(new TreeNode(issueType.Name, 
													MapIssueTypeToImageIndex(issueType), 
													MapIssueTypeToImageIndex(issueType)));

			ICollection<IIssue> issuesColl = (ICollection<IIssue>)appScan.Scan.ScanData.AppTreeRoot.GetIssues(issueType);

			// Add them all to the list
			foreach (IIssue issue in issuesColl)
			{
				TreeNode treeNode = new TreeNode(DefectLoggerBase.GetEntityDesc(issue.Entity), 1, 1);
				treeNode.Tag = issue;
				treeIssueSelector.Nodes[0].Nodes.Add(treeNode);
			}

			treeIssueSelector.EndUpdate();

		}

		private void CancelBtn_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void OkBtn_Click(object sender, EventArgs e)
		{
			TreeNode selectedNode = treeIssueSelector.SelectedNode;
			if (selectedNode == null || selectedNode.Tag == null)
			{
				MessageBox.Show("Please select an item, or press Cancel");
				return;
			}

			// We have an item - mark it and close.
			_selectedIssue = selectedNode.Tag as IIssue;
			Close();
		}

		private void IssueSelector_DoubleClick(object sender, System.EventArgs e)
		{
			OkBtn_Click(sender, e);
		}

		private void IssueSelector_Shown(object sender, System.EventArgs e)
		{
			// try to select the first issue in the tree
			TreeNode treeNode = treeIssueSelector.TopNode;
			if (treeNode != null && treeNode.FirstNode != null)
			{
				treeNode = treeNode.FirstNode;
				treeIssueSelector.SelectedNode = treeNode;
				treeIssueSelector.TopNode.Expand();
				treeIssueSelector.Select();
			}
		}
	}
}